import axios from "axios";

export default {
    state: {
        posts: [],
        pager: {
            _page: 1,
            _limit: 15
        },
        finished: false
    },
    mutations: {
        SET_POSTS(state, data) {
            state.posts = [...state.posts, ...data]
            if (data.length < state.pager._limit) {
                state.finished = true
            }
        },
        SET_PAGE(state, page) {
            state.pager._page = page
        },
    },
    actions: {
        getPostsAction({commit, state}) {
            return axios({
                url: 'https://jsonplaceholder.typicode.com/posts',
                params: { // ?_page=2&_limit=10
                    _page: state.pager._page,
                    _limit: state.pager._limit
                }
            }).then(res => {
                commit('SET_POSTS', res.data)
            })
        },
        getPostsNextPage({commit, state, dispatch}) {
            // 修改页码
            commit('SET_PAGE', state.pager._page + 1)
            console.log(state.pager)
            // 请求下一页数据
            return dispatch('getPostsAction')
        }
    },
    namespaced: true, // 命名空间
}
